﻿using iTool.Cloud.DataSearch.ServiceProvider;

using Lucene.Net.Store;

using Orleans;

namespace iTool.Cloud.DataSearch.DirectoryProvider
{
    public class iToolCloudLock : Lock
    {
        readonly IClusterClient iCluster;
        readonly ILockService lockService;
        readonly bool isLocalService;
        readonly long tableNameHash;
        readonly string lockName;

        public iToolCloudLock(long tableNameHash, string lockName, IClusterClient iCluster, bool isLocalService)
        {
            this.isLocalService = isLocalService;
            this.tableNameHash = tableNameHash;
            this.lockName = lockName;
            this.iCluster = iCluster;
            this.lockService = 
                    this.isLocalService ? IDirectoryServiceFactory<LockService>.GetService(tableNameHash, lockName) :
                this.iCluster.GetGrain<ILockService>(tableNameHash, lockName);
        }
        // 是否存在锁
        public override bool IsLocked() => this.lockService.IsLockedAsync().Result;

        // 获取锁
        public override bool Obtain() => this.lockService.ObtainAsync().Result;

        // 释放锁
        protected override async void Dispose(bool disposing)
        {
            if(this.isLocalService) IDirectoryServiceFactory<LockService>.Dispose(tableNameHash, lockName);
            else await this.lockService.DisposeAsync();
        }
    }
}
